19. Know When to Quit Solution

Solution

One solution is to add the break statment after the money value has been modified in all possible cases:

public int martingale() {
 int money = 1000;
 int target = 1200;
 int bet = 10;
 while (money > bet) {
  boolean win = play();
  if (win) {
   money += bet;
   bet = 10;
  } else {
   money -= bet;
   bet *= 2;
  }
  // Add the break here:
  if(money >= target)
     break;
 }
 return money;
}

However, you might find other spots as to where you can add the break that might still work! The key is to make sure that it's checked in ALL possible cases.

Note: You can actually add this extra check inside the while condition itself making it:

while (money>bet && money<target)

But the goal of this exercise was to practice using the break statment, which give you the extra flexibility to break from the while loop at anytime inside the code block instead of waiting for another iteration.